import socket
import os


from .config import server_address
from .config import BUFFSIZE
from .config import SYNC

from .ProcessData import getlines
from .ProcessData import resolve

from .ControlList import ControlList
# from .Path import PathData
import time
from .ControlType import CTRL_TYPE
from .util import *


import subprocess
import re
import pyautogui
import time
from PIL import Image
import pytesseract
from subprocess import Popen



count=1
def NewServer(initOcrStr,resultDir,logF,resultFile,pos):
    """
    和WineServer交互信息
    """

    try:
        os.unlink(server_address)
    except OSError:
        if os.path.exists(server_address):
            raise
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sock.bind(server_address)
    sock.listen(1)

    while True:
        try:
            print("wait for a connection")
            connection, _ = sock.accept()
            ctrls = ControlList()
            rin = ""
            print("get a connection")

          
            print("rewrite resultFile....")
            resF=open(resultFile,"w")
            # get the app name
            if not os.path.isfile(SYNC):
                raise RuntimeError("file {} NOT exists!".format(SYNC))
            appName = None
            with open(SYNC, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                if len(lines) != 1:
                    raise RuntimeError("file {} wrong format!".format(SYNC))
                appName = lines[0].strip()
            # wait time for app start
            time.sleep(15)
            print("sleep end...")
            
            opened,notErrWindow=isNewWindowOpend(initOcrStr,resultDir,logF,pos,appName)
            if not opened:
                print("Failed: no new windows")
                logF.write(getContent("{},open result".format(appName),"Failed"))
                resF.write("{},Failed\n".format(appName))
            else:
                if notErrWindow:
                    print("Succeed: no found error info")
                    resF.write("{},Succeed\n".format(appName))
                    logF.write(getContent("{},open result".format(appName),"Succeed"))
                    screenshotSenseSize(resultDir,appName,pos)
                else:
                    print("found error info")
                    click_enter(5)
                    opened,notErrWindow=isNewWindowOpend(initOcrStr,resultDir,logF,pos,appName)
                    if not opened:
                        print("Failed: no new windows after input enter")
                        logF.write(getContent("{},open result".format(appName),"Failed"))
                        resF.write("{},Failed\n".format(appName))
                    else:
                        # if notErrWindow:
                        #     print("Succeed: no found error info after click")
                        #     resF.write("{},Succeed\n".format(appName))
                        #     logF.write(getContent("{},open result".format(appName),"Succeed"))
                        #     screenshotSenseSize(resultDir,appName,pos)
                        # else:
                        #     print("Failed: found error info after click")
                        #     resF.write("{},Failed\n".format(appName))
                        #     logF.write(getContent("{},open result".format(appName),"Failed"))
                        
                        # click button 5 times 
                        failed_res=False
                        for i in range(5):
                            if failed_res:
                                break
                            connection.sendall("send".encode(encoding='utf-8'))
                            while True:
                                print("before get data")
                                data = connection.recv(BUFFSIZE)
                                print("get data")
                                if data:
                                    data = data.decode(encoding='utf-8')
                                    print(data)
                                    logF.write(getContent("get buttons",data))
                                    lines, rin = getlines(rin+data)
                                    end = resolve(lines, ctrls)
                                    if end:
                                        break
                                    else:
                                        raise ValueError("client broken socket!")
                            ctrls.show()
                            print(clickNames)
                            for name in clickNames:
                                # button
                                res,rawButton=findButton(ctrls[CTRL_TYPE[1]],name)
                                if not res:
                                    print("not found click button "+name)
                                    continue
                                else:
                                    print("click button "+rawButton)
                                    ctl=ctrls[CTRL_TYPE[1]][rawButton]
                                    ctl.click()
                                    print("click button end")
                                    time.sleep(5)
                                    x,y,w,h=get_active_window_rect()
                                    screenshotSenseSize(resultDir,appName,(x,y,w,h))
                                    if x==pos[0] and y==pos[1] and w==pos[2] and h==pos[3]:
                                        failed_res=True
                                        break
                        if failed_res:
                            print("Failed,window close after click button")
                            logF.write(getContent("{},Failed".format(appName),"window close after click button"))
                            resF.write("{},Failed\n".format(appName))
                        else:
                            print("Succeed,window not close after click ok")
                            logF.write(getContent("{},Succeed".format(appName),"window not close after click ok"))
                            resF.write("{},Succeed\n".format(appName))

           
            connection.close()
        except Exception as e:
            print(e)
            logF.write(getContent("{},open result".format(appName),"Failed"))
            resF.write("{},Failed\n".format(appName))
            connection.close()
        logF.flush()
        resF.flush()
        resF.close()



apps=[
    [
        "gnome-calculator"
    ]
]


errorMsg=[
    "error",
    "fail",
    "expire",
    "purchase",
    "try",
]
errorMsgChinese=[
    "error",
    "fail",
    "expire",
    "purchase",
    "try",
    u"错误",
    u"失败",
    u"严重",
    u"问题",
    u"抱歉",
    u"缺陷",
]

clickNames=[
    "next",
    "continue",
    "try",
    "later",
    "evaluat",
    "agree",
    "test",
    "ok",
    "确认",
    "关闭",
    "试用",
    "下一步",
]

# 第一个bool 表示是否有窗口打开，第二bool 表示窗口是否error 信息
def isNewWindowOpend(initOcrMsg,appResultDir,logF,pos,appName):
   
    openedImage=os.path.join(appResultDir,"opened-"+appName+".png")
    x,y,w,h=get_active_window_rect()

    print(x,y,w,h)
    # judge different
    if x==pos[0] and y==pos[1] and w==pos[2] and h==pos[3]:
        # is same
        print("open exe file failed,because no new windows")
        logF.write(getContent("open app failed","open exe file failed,because no new windows"))
        return False,False
    screenshot((x,y,w,h),openedImage,False)
    print("English ocr....")
    logF.write(getContent("screenshot openedImage",openedImage))
    openedOcrStr=ocrImage(openedImage)
    openedOcrStr=openedOcrStr.lower()
    print("Chinese ocr....")
    logF.write(getContent("screenshot openedImage ocr",openedOcrStr))
    openedOcrStrChinese=ocrImageChinese(openedImage)
    openedOcrStrChinese=openedOcrStrChinese.lower()

    logF.write(getContent("screenshot openedImage ocr chinese",openedOcrStrChinese))

    for msg in errorMsg:
        if openedOcrStr.find(msg)!=-1:
            return True,False
    for msg in errorMsgChinese:
        if openedOcrStrChinese.find(msg)!=-1:
            return True,False

    
    return True,True

def screenshotSenseSize(appResultDir,appName,pos):
    openedImage=os.path.join(appResultDir,"opened-"+appName+".png")
    screenshot(pos,openedImage,True)

def findButton(buttons,button):
    newbutton=button
    newbutton=button.lower()
  
    for each in buttons.keys():
        neweach=each
        neweach=neweach.lower()
        print(neweach,newbutton)
        res=neweach.find(newbutton)
        if res >=0:
            return True,each
    return False,""
